Micron Document
Livres et Wikis | Archives | Info


JavaScript syntax
part 5/30 Β· 107.0 KB total
layout: Wide Β· Narrow Β· Centered
──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
When assigning an identifier, JavaScript goes through exactly the same
process to retrieve this identifier, except that if it is not found in
the global scope, it will create the "variable" in the scope where it
was created.cite-ref-9[9] As a consequence, a variable never declared will be
global, if assigned. Declaring a variable (with the keyword var) in the
global scope (i.e. outside of any function body (or block in the case of
let/const)), assigning a never declared identifier or adding a property
to the global object (usually window) will also create a new global
variable.

Note that JavaScript's strict mode forbids the assignment of an
undeclared variable, which avoids global namespace pollution.

Examples

Here are some examples of variable declarations and scope:

var x1 = 0; // A global variable, because it is not in any function
let x2 = 0; // Also global, this time because it is not in any block
function f() {
var z = 'foxes', r = 'birds'; // 2 local variables
m = 'fish'; // global, because it was not declared anywhere before
function child() {
var r = 'monkeys'; // This variable is local and does not affect the
"birds" r of the parent function.
z = 'penguins'; // Closure: Child function is able to access the
variables of the parent function.
}
twenty = 20; // This variable is declared on the next line, but usable
anywhere in the function, even before, as here
var twenty;
child();
return x1 + x2; // We can use x1 and x2 here, because they are global
}
f();
console.log(z); // This line will raise a ReferenceError exception,
because the value of z is no longer available

for (let i = 0; i < 10; i++) console.log(i);
console.log(i); // throws a ReferenceError: i is not defined

for (const i = 0; i < 10; i++) console.log(i); // throws a TypeError:
Assignment to constant variable
for (const i of [1,2,3]) console.log(i); //will not raise an exception.
i is not reassigned but recreated in every iteration
const pi; // throws a SyntaxError: Missing initializer in const
declaration


──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────